import { userinfo } from '@/stores/counter';
import { ElMessage } from 'element-plus';
import request from './useRequests';

export default function articleStar() {
  const user = userinfo();

  //修改点赞信息
  async function setStar(articleId: number, userId: number) {
    try {
      let res = await request({
        method: 'get',
        url: 'favorite/fav',
        params: {
          articleId: articleId,
          userId: userId,
        },
      });

      console.log(res.data);
      if (res.data.status) {
        ElMessage({
          showClose: true,
          message: '修改点赞成功',
          type: 'success',
        });
        return true;
      } else {
        ElMessage({
          showClose: true,
          message: '点赞失败',
          type: 'error',
        });
        return false;
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '点赞时发生未知错误',
        type: 'error',
      });
      return false;
    }
  }

  //加载页面时获取点赞信息
  async function getStar(articleId: number, userId: number) {
    try {
      let res = await request({
        method: 'get',
        url: 'favorite/status',
        params: {
          articleId: articleId,
          userId: userId,
        },
      });
      if (res.data.status) {
        return res.data.data == 1;
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '获取点赞信息时发生未知错误',
        type: 'error',
      });
    }
  }

  async function getFavArticle() {
    const userId = user.baseInfo.id;
    if (!userId) {
      return;
    }

    try {
      const res = await request({
        method: 'get',
        url: `/favorite/list`,
        params: {
          page: user.fav.page,
          size: 3,
          userId: userId,
        },
      });

      if (res.data.status) {
        user.fav.list.push(...res.data.data.items);
        user.fav.total = res.data.data.total;
      } else {
        ElMessage({
          showClose: true,
          message: '后台：获取点赞文章信息时发生未知错误',
          type: 'error',
        });
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '前台：获取点赞文章信息时发生未知错误',
        type: 'error',
      });
    }
  }

  return {
    setStar,
    getStar,
    getFavArticle,
  };
}
